__author__ = 'zoulida'
import shelve
from Config import FILEPATH#这个Config在父文件夹，路径优先即可覆盖。

def saveShelve(key, content):
    filepath = FILEPATH.SHELVEDIR.value
    shelveDict = shelve.open(filepath)
    shelveDict[key] = content
    shelveDict.close()

def getShelve(key):
    filepath = FILEPATH.SHELVEDIR.value
    shelveDict = shelve.open(filepath)
    content = shelveDict[key]
    shelveDict.close()
    return content

def getShelveData(name, fun, args, kwargs):#

    #调用方法
    '''import tools.shelveTool as st
    arg = '20210101', '20210602'
    st.getShelveData('test', getEveryMonthFirstOpenday, arg )'''

    #name = dateDay + '_' +str(percentage)
    #print(name)
    #from rqalpha.const import FILEPATH
    #dirstr = FILEPATH.SHELVEDIR.value
    #filepath = dirstr + 'scanZToneDay3'
    from Config import FILEPATH#这个Config在父文件夹，路径优先即可覆盖。
    filepath = FILEPATH.SHELVEDIR.value
    #filepath = 'F:\\quantdata\\quantaxis'
    shelveDict = shelve.open(filepath)
    if name in shelveDict:
        listResult = shelveDict[name]
    else:
        #listResult = haveBeenGreaterThanbyOneDayCodelist(dateDay, percentage)
        listResult = fun(*args, **kwargs)
        if listResult is not None and len(listResult) != 0:
            shelveDict[name] = listResult
    shelveDict.close()
    return listResult

def shelve_me(fn):#参数只能是字符串，不然不能作为key区分
    def _wrapper(*args, **kwargs):
        shelvekey = 'shelve_me'
        shelvekey += fn.__name__
        #print(str(args[1:]))
        shelvekey += "".join(args)
        shelvekey += "".join(str(kwargs))
        print(shelvekey)
        #print(args)
        return getShelveData(shelvekey, fn, args, kwargs)
        #fn(*args, **kwargs)
    return _wrapper

def shelve_me_for_class(fn):#参数只能是字符串，不然不能作为key区分
    def _wrapper(*args, **kwargs):
        shelvekey = 'shelve_me'
        shelvekey += fn.__name__
        #print(str(args[1:]))
        shelvekey += "".join(args[1:])
        shelvekey += "".join(str(kwargs))
        print(shelvekey)
        #print(args)
        return getShelveData(shelvekey, fn, args, kwargs)
        #fn(*args, **kwargs)
    return _wrapper

@shelve_me
def testWrapper(key):
    print('testWrapper done')
    return key

@shelve_me
def testWrapperKwargs(key1 = 'keyA', key2 = 'keyB'):
    print('testWrapperKwargs done')
    return key1


if __name__ == '__main__':
    #print(testWrapper('zld5'))
    #print(testWrapperKwargs(key1 = 'keyC', key2 = 'keyD'))
    #第一次执行 有testWrapper done 说明函数被执行
    #shelve_metestWrapperzld5
    #testWrapper done
    #zld5

    #第二次执行，没有testWrapper done，说明没有被执行。直接返回了数据。
    #shelve_metestWrapperzld5
    #zld5

    saveShelve('hello', '5555555')
    saveShelve('hello', '66666666')
    print(getShelve('hello'))